// 白名单
const whiteList = [
	'/',
	'/pages/home/index',
	'/pages/product/index',
	'/pages/square/index',
	'pages/user/index',
	{
		pattern: /^\/pages\/login\/*/
	}
]

/** 路由模块 */
export default class Router {
	/**
	 * 路由跳转
	 */
	static push(url, data) {
		let data_str = ''
		console.log(data)
		if (data) {
			data_str += '?'
			console.log('111')
			for (let key in data) {
				if (typeof data[key] == 'string') {
					data_str += (key + '=' + data[key])
				} else {
					data_str += (key + '=' + JSON.stringify(data[key]))
				}
			}
		}
		uni.navigateTo({
			url: url + data_str,
			animationType: 'pop-in',
			animationDuration: 200,
			fail: (res) => {
				console.log('执行')
				uni.switchTab({
					url: url + data_str
				});
			}
		})
	}
	/** 路由鉴权*/
	routerCheck() {
		const list = ['navigateTo', 'redirectTo', 'reLaunch', 'switchTab']
		list.forEach(item => {
			uni.addInterceptor(item, {
				invoke(e) {
					const url = e.url.split('?')[0]
					// 判断当前窗口是白名单，如果是则不重定向路由
					let pass
					if (whiteList) {
						pass = whiteList.some((item) => {
							if (typeof(item) === 'object' && item.pattern) {
								return item.pattern.test(url)
							}
							return url === item
						})
					}
					// 后续直接删除
					pass = true
					// 不是白名单并且没有token
					if (!pass && !userStore().token) {
						uni.showToast({
							title: '请先登录',
							icon: 'none'
						})
						uni.navigateTo({
							url: "/pages/login/index"
						})
						return false
					}
					return true
				},
				fail(err) {
					// console.log(err)
				}
			})
		})
	}
}